<?php
namespace App\Model;

use Illuminate\Database\Eloquent\Model; 
use Illuminate\Support\Facades\DB;
use App\Model\{Hengfeng,Moneylog,Trad,BorrowRepay};
use Illuminate\Support\Facades\Crypt;
use App\Libraries\vendor\Sms;
use Illuminate\Support\Facades\Redis;

class User extends Model
{
	
	public static function separat_format(&$list){
        $tree_ids = get_array_keys($list->items(),'tree_id');
        $uids = get_array_keys($list->items(),'uid');
        $users = DB::table('userdata')->whereIn('id',$uids)->get()->toArray();
        $users = arrays_set_key($users,'id');

        $profits = DB::table('data_statistics')->select('uid','money_all')->whereIn('uid',$uids)->get()->toArray();
        $profits = arrays_set_key($profits,'uid');
        $user_levels = DB::table('user_tree')->select(['uid','user_level'])->whereIn('uid',$tree_ids)->get()->toArray();
        $user_levels = arrays_set_key($user_levels,'uid');
        /*
        $huoyue = DB::table('everyday_contribution')->select(DB::raw('count(id) as count,uid'))->where([
            ['day','=',date('Ymd')],
            ['frequency_all','>',2]
        ])->groupBy('uid')->get()->toArray();
        $huoyue = arrays_set_key($huoyue,'uid');
        */
        #风险等级
        $riskGrade = Config::get_config_bykey('user_risk_level_riskGrade');
        $risk = DB::table('user_risk_level')->whereIn('uid',$uids)->get()->toArray();
        $risk = arrays_set_key($risk,'uid');
        foreach ($list->items() as $item) {
            $item->user = $users[$item->uid];
            #总收益 
            #$profits = DB::table('data_statistics')->where('uid',$item->uid)->orderBy('id','desc')->first(['money_all']);
            $item->profit = $profits[$item->uid]->money_all??0;
            if(isset( $user_levels[$item->tree_id]) ){
                $item->top_uid = $user_levels[$item->tree_id]->user_level==2?$item->tree_id:'';
            }else{
                $item->top_uid='';
            }
            
            $tdids = DB::table('user_tree')->where('pid',$item->uid)->pluck('uid')->toArray();
            $item->td_huoyue = DB::table('everyday_contribution')->select(DB::raw('count(id) as count,uid'))
            ->whereIn('uid',$tdids)
            ->where([
                ['day','=',date('Ymd')],
                ['frequency_all','>',2]
            ])->count();
            $tsids = DB::table('user_tree')->where([
                ['left','>',$item->left],
                ['right','<',$item->right],
                ['hight','=',2],
                ['tree_id','=',$item->tree_id],
            ])->pluck('uid')->toArray();
            $item->ts_huoyue = DB::table('everyday_contribution')->select(DB::raw('count(id) as count,uid'))
            ->whereIn('uid',$tsids)
            ->where([
                ['day','=',date('Ymd')],
                ['frequency_all','>',2]
            ])->count();

            #总活跃数
            $huoyue_uids = DB::table('user_tree')->where([
                ['tree_id','=',$item->tree_id],
                ['left','>',$item->left],
                ['right','<',$item->right],
            ])->pluck('uid');
            $item->total_huoyue = DB::table('everyday_contribution')->whereIn('uid',$huoyue_uids)
            ->where([
                ['day','=',date('Ymd')],
                ['frequency_all','>',2]
            ])->count();
            #风险等级
            $item->risk= $risk[$item->uid]??null;
            if(isset($item->risk->riskGrade)){
                $item->risk->riskGrade = $riskGrade[$item->risk->riskGrade]??null;
            }
        }
    }

    public static function apply_parther_format(&$list){
        $uids = get_array_keys($list->items(),'uid');
        $tree = DB::table('user_tree')->select(['uid','tree_id','left','right','td_count','ts_count','all_count'])->whereIn('uid',$uids)->get()->toArray();
        $tree = arrays_set_key($tree,'uid');

        foreach ($list->items() as $item) {
            $item->user =  $tree[$item->uid];
            $tdids = DB::table('user_tree')->where('pid',$item->uid)->pluck('uid')->toArray();
            $item->td_huoyue = DB::table('everyday_contribution')->select(DB::raw('count(id) as count,uid'))
            ->whereIn('uid',$tdids)
            ->where([
                ['day','=',date('Ymd')],
                ['frequency_all','>',2]
            ])->count();

            /*
            $tsids = DB::table('user_tree')->where([
                ['left','>',$item->user->left],
                ['right','<',$item->user->right],
                ['hight','=',2],
                ['tree_id','=',$item->user->tree_id],
            ])->pluck('uid')->toArray();
            $item->ts_huoyue = DB::table('everyday_contribution')->select(DB::raw('count(id) as count,uid'))
            ->whereIn('uid',$tsids)
            ->where([
                ['day','=',date('Ymd')],
                ['frequency_all','>',2]
            ])->count();

            #总活跃数
            $huoyue_uids = DB::table('user_tree')->where([
                ['tree_id','=',$item->user->tree_id],
                ['left','>',$item->user->left],
                ['right','<',$item->user->right],
            ])->pluck('uid');
            $item->total_huoyue = DB::table('everyday_contribution')->whereIn('uid',$huoyue_uids)
            ->where([
                ['day','=',date('Ymd')],
                ['frequency_all','>',2]
            ])->count();
            */
        }
    }

    /**
     * 收益列表
     */
    public static function money_format(&$list){
        $uids = get_array_keys($list->items(),'uid');
        $users = DB::table('user_tree')->whereIn('uid',$uids)->get()->toArray();
        $users = arrays_set_key($users,'uid');
        foreach ($list->items() as $item) {
            $item->user = $users[$item->uid];
        }
    }

    /**
     * 升级为合伙人
     */
    public static function separate_tree($uid){
        $user = DB::table('user_tree')->where('uid',$uid)->first();
        if (empty($user)) return false;
        if($user->user_level==2) return false;
        $jia = $user->left - 1;
        $tree_id = $user->tree_id;
        $width = ($user->right - $user->left + 1);
        
        $from = DB::table('user_tree')->where([
            ['tree_id','=',$tree_id],
            ['left','<',$user->left],
            ['right','>',$user->right],
            ['user_level','=',2],
        ])->first();

        DB::beginTransaction();
        #修改自己子节点
        $step3 = DB::table('user_tree')->where([
            ['tree_id','=',$user->tree_id],
            ['left','>=',$user->left],
            ['right','<=',$user->right],
        ])->update([
            'left'=>DB::raw("`left`-$jia"),
            'right'=>DB::raw("`right`-$jia"),
            'hight'=>DB::raw("`hight`-{$user->hight}"),
            'tree_id'=>$user->uid,
            'from_uid'=>isset($from->uid) ? $from->uid : 0,
        ]);
        #修改自己
        $step4 = DB::table('user_tree')->where('uid',$uid)->update([
            'user_level'=>2,
            'pid'=>0,
            'from_uid'=>isset($from->uid) ? $from->uid : 0,
            'up_partner_time'=>time(),
        ]);

        #修改右节点
        $step1 = DB::table('user_tree')->where([
            ['tree_id','=',$user->tree_id],
            ['left','>',$user->right]
        ])->update([
            'left'=>DB::raw("`left`-$width"),
            'right'=>DB::raw("`right`-$width")
        ]);
        #修改父节点
        $step2 = DB::table('user_tree')->where([
            ['tree_id','=',$user->tree_id],
            ['left','<',$user->left],
            ['right','>',$user->right],
        ])->update([
            'right'=>DB::raw("`right`-$width")
        ]);
        
        #dd($step1,$step2 , $step3 , $step4);
        if ($step1 !== false && $step2!==false && $step3!==false && $step4) {
            DB::commit();
            #入库消息 && 发送通知
            $day = date('Y/m/d H:i');
            $add_msg = DB::table('message')->insert([
                'uid'=>$uid,
                'is_system'=>0,
                'type'=>3,
                'title'=>'恭喜您升级为合伙人',
                'content'=>'恭喜您，在' . $day . '达到升级合伙人条件，我们现已将您的账户升级为合伙人！',
                'add_time'=>time(),
                'click_url'=>"songshu://songshutoutiao.com/native?url=vip_center&need_login=1",
                'button_name'=>'去查看',
                'show_type'=>3,
            ]);
            if($add_msg){
                $data = array(
                        'work_type' => "4",
                        'title' => "恭喜您升级为合伙人",
                        'text' => "恭喜您，在" . $day . "达到升级合伙人条件，我们现已将您的账户升级为合伙人！",
                        'reg_id' => $uid,
                        'list' => array(
                            'work_type'=>"4",
                            'type'=>"2",//1升级为超级会员  2升级为合伙人
                            'click_url'=>'songshu://songshutoutiao.com/native?url=partner_login&need_login=1'
                        )
                    );
                $data = json_encode($data);
                Redis::rpush('queue:jpush',$data);
                Redis::rpush('songshu:queue',json_encode([
                    'work_type'=>7,
                    'data'=>[
                        $user->uid,$tree_id
                    ]
                ]));
            }
            #修改合伙人数量
            if( isset($from->uid) && $from->uid>0 ){
                DB::table('user_tree')->where('uid',$from->uid)->increment('from_count');
            }
            return true;
        }
        DB::rollBack();
        return false;
    }


    /**
     * 合伙人当月预估收益
     */
    public static function nowmonth($uid){
        $t0 = date('t');
        $day = date('Ym00');
        //查询本月第一次产生收益的日期
        $tmp = DB::table('partner_daily_data')->where('uid',$uid)->where('day','>',$day)->first();
        if (empty($tmp)) {
            $this_month = '￥0.00';
        } else {
            $day_2 = $tmp->day - $day;
            $day_3 = $t0 - $day_2+1;//总计可产生收益天数
            //计算产生了几天数据
            $day_4 = date('Ymd');
            $day_5 = $day_4 - $tmp->day + 1;
            $this_month = DB::table('partner_daily_data')->where('uid',$uid)->where('day','>',$day)->sum('coin_all');
            $money_1 = ($this_month / $day_5) * $day_3;
            $this_month = "￥" . number_format((floor($money_1 / 100) / 10), 2, null, '');
        }
        return $this_month;
    }

    /**
     * 合伙人提现拒绝
     */
    public static function partner_cash_refund($id,$msg){
        $info = DB::table('partner_cash')->where('id',$id)->first();
        if(empty($info)){
            return false;
        }
        DB::beginTransaction();
        $bool = DB::table('partner_cash')->where('id',$id)->update([
                'state'=>2,
                'msg'=>$param['msg']
            ]);
        $tree = DB::table('user_tree')->where('uid',$info->uid)->lockForUpdate()->first(['uid','money']);
        $update_money = DB::table('user_tree')->where('uid',$info->uid)->update([
            'money'=>DB::raw("`money`+".$info->money),
        ]);
        $insert_moneylog = DB::table('partner_moneylog')->insert([
            'uid'=>$info->uid,
            'affect'=>$info->money,
            'add_time'=>time(),
            'current_money'=>$tree->money+$info->money,
            'type'=>5,
            'desc'=>'拒绝提现'
        ]);

        if($bool && $update_money!==false && $insert_moneylog!==false){
            DB::commit();
            return true;
        }
        DB::rollBack();
        return false;
    }

    /**
     * 普通用户提现拒绝
     */
    public static function tx_refund($id,$msg=''){
        $info = DB::table('txdata')->where('id',$id)->first();
        if(empty($info)){
            return false;
        }
        DB::beginTransaction();
        $bool = DB::table('txdata')->where('id',$id)->update([
                'state'=>2,
            ]);
        $update_money = DB::table('userdata')->where('id',$info->uid)->update([
            'money'=>DB::raw("`money`+".$info->money)
        ]);
        if($bool && $update_money!==false){
            DB::commit();
            return true;
        }
        DB::rollBack();
        return true;
    }
}